﻿using System.Collections.Generic;
using System.Data;
using System.Text;

using Common;
using DAL;

namespace Core
{
    public class TableInfo
    {
        public List<ColumnInfo> Columns = new List<ColumnInfo>();

        public List<ColumnInfo> PkColumns = new List<ColumnInfo>();
        public List<ColumnInfo> NonPkColumns = new List<ColumnInfo>();

        public List<ColumnInfo> IdentityColumns = new List<ColumnInfo>();
        public List<ColumnInfo> NonIdentityColumns = new List<ColumnInfo>();//For Insert

        public List<ColumnInfo> UpdateColumns = new List<ColumnInfo>();//For Update

        public bool HasIdentityColumn
        {
            get { return this.IdentityColumns.Count > 0; }
        }

        public bool IsTable //Not View
        {
            get { return this.Table_Type == TablePropName.TABLE_TYPE__BASE_TABLE; }
        }

        public string Name = null; //TableName
        public string Catalog = null; //DataBase
        public string Table_Schema = null;//Owner
        public string Table_Type = null;//Table or View

        public SchemaHeler SchemaHeler = null;

        public TableInfo(SchemaHeler schemaHeler, string tableName, string[] tableRestriction)
        {
            this.SchemaHeler = schemaHeler;
            DataTable tableSchema = this.SchemaHeler.GetTables(tableRestriction);
            if (tableSchema.Rows.Count == 1)
            {
                DataRow dr = tableSchema.Rows[0];
                this.Catalog = dr[TablePropName.TABLE_CATALOG].ToString();
                this.Table_Schema = dr[TablePropName.TABLE_SCHEMA].ToString();
                this.Name = dr[TablePropName.TABLE_NAME].ToString();
                this.Table_Type = dr[TablePropName.TABLE_TYPE].ToString();
            }

            DataTable columnSchema = this.SchemaHeler.GetSchemaTable(tableName, this.Table_Type);

            for (int i = 0; i < columnSchema.Rows.Count; i++)
            {
                DataRow dr = columnSchema.Rows[i];
                var col = new ColumnInfo(dr, this);
                this.Columns.Add(col);

                if (col.IsKey)
                {
                    this.PkColumns.Add(col);
                }
                else
                {
                    this.NonPkColumns.Add(col);
                }

                if (col.IsIdentity)
                {
                    this.IdentityColumns.Add(col);
                }
                else
                {
                    this.NonIdentityColumns.Add(col);
                }

                if (!col.IsKey && !col.IsIdentity)
                {
                    this.UpdateColumns.Add(col);
                }
                
            }
        }
    }
}
